<!doctype html>
<html lang="zh-cn">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>注册</title>
    <link rel="stylesheet" href="/static/font/iconfont.css">
    <link rel="stylesheet" href="/static/css/bootstrap.css">
    <link rel="stylesheet" href="/static/css/twitter.css">
</head>

<body class="d-flex w-100">
    <div class="auth-box mx-auto text-center">
        <a href="/">
            <img class="auth-logo mb-4" src="/static/img/logo.png" alt="">
        </a>
        <h1 class="mb-4 h4 fw-bold text-center">注册帐户</h1>
        <form id="authForm" method="post">
            <input type="hidden" name="csrf_token" value="{:csrf_token()}">
            <div class="form-floating mb-4">
                <input type="text" class="form-control" id="username" name="username" value="{:old('username')}"
                    placeholder="用户名" required autofocus>
                <label for="username" class="error-message">用户名</label>
            </div>
            <div class="form-floating mb-4">
                <input type="password" class="form-control" id="password" name="password" value=""
                    placeholder="密码" required>
                <label for="password" class="error-message">密码</label>
            </div>
            <div class="form-floating mb-4 position-relative">
                <input type="text" class="form-control" id="captcha" name="captcha" placeholder="验证码" required>
                <label for="captcha" class="error-message">验证码</label>
                <img id="resetCaptcha" class="position-absolute auth-captcha cursor-pointer" src="/auth/captcha" alt=""
                    data-bs-toggle="tooltip" data-bs-title="点击刷新验证码">
            </div>
            <button type="submit" class="btn btn-primary py-3 w-100 shadow" id="submit-btn">注册</button>
            <div class="d-flex align-items-center justify-content-center mt-3">
                <span>已有账户？</span>
                <a href="/login" class="btn btn-link">登录</a>
            </div>
        </form>
    </div>
    <script src="/static/js/jquery.min.js"></script>
    <script src="/static/js/bootstrap.bundle.min.js"></script>
    <script src="/static/js/twitter.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const rules = {
                username: {
                    regex: /^.{3,16}$/,
                    message: '用户名长度为3-16个字符'
                },
                password: {
                    regex: /^.{6,16}$/,
                    message: '密码长度为6-16个字符'
                },
                captcha: {
                    regex: /^.{4}$/,
                    message: '验证码为 4 个字符'
                },
            };

            const captchaImg = document.getElementById('resetCaptcha');
            const submitButton = document.getElementById('submit-btn');
            const form = document.getElementById('authForm');

            function validate(field) {
                const input = document.getElementById(field);
                const value = input.value;
                const rule = rules[field];
                const errorDiv = input.nextElementSibling;

                if (!rule.regex.test(value)) {
                    errorDiv.textContent = rule.message;
                    input.classList.add('is-invalid');
                    return false;
                } else {
                    errorDiv.textContent = input.placeholder || '';
                    input.classList.remove('is-invalid');
                    return true;
                }
            }

            function validateAllFields() {
                let isValid = true;
                Object.keys(rules).forEach(field => {
                    if (!validate(field)) {
                        isValid = false;
                    }
                });
                return isValid;
            }

            function handleFormSubmission(event) {
                event.preventDefault();

                if (!validateAllFields()) {
                    toast('请检查表单输入', 'danger');
                    return;
                }

                const formData = new FormData(this);
                submitButton.disabled = true;

                fetch('/register/submit', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'Accept': 'application/json'
                    }
                })
                    .then(response => response.json())
                    .then(res => {
                        if (res.status === 'success') {
                            toast(res.message, 'success');
                            setTimeout(() => {
                                document.referrer === "" ? (window.location.href = "/") : window.history.back();
                            }, 2000);
                        } else {
                            captchaImg.setAttribute('src', '/auth/captcha?' + Math.random());
                            toast(res.message, 'danger');
                        }
                        submitButton.disabled = false;
                    })
                    .catch(error => {
                        toast('提交失败，请稍后再试', 'danger');
                        setTimeout(() => {
                            location.reload();
                        }, 2000);
                        submitButton.disabled = false;
                    });
            }

            // 使用事件委托绑定输入事件，实时验证
            form.addEventListener('input', function (event) {
                if (event.target.classList.contains('form-control')) {
                    const fieldId = event.target.id;
                    validate(fieldId);
                }
            });

            form.addEventListener('submit', handleFormSubmission);
        });
    </script>
</body>

</html>